package com.waterfairy.permission

import android.content.pm.PackageManager
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import org.json.JSONArray
import org.json.JSONObject

/**
 * @user water_fairy
 * @mail 995637517@qq.com
 * @date 2021/12/24 5:17 下午
 * @info
 */
class PermissionHandler(
    val result: MethodChannel.Result,
    val activityPluginBinding: ActivityPluginBinding?,
    val permissions: Array<String>,
    val requestCode: Int
) : PluginRegistry.RequestPermissionsResultListener {

    init {
        activityPluginBinding?.addRequestPermissionsResultListener(this)
    }

    fun handle() {
        activityPluginBinding?.activity?.let { activity ->
            PermissionUtils.requestPermissionList(
                activity,
                permissions,
                requestCode
            )
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>?,
        grantResults: IntArray?
    ): Boolean {
        return if (requestCode == this.requestCode) {
            val jsonArray = JSONArray()
            grantResults?.let {
                permissions?.forEachIndexed { index, permission ->
                    val jsonObject = JSONObject()
                    jsonObject.put("requestCode", requestCode)
                    jsonObject.put("permission", permission)
                    jsonObject.put(
                        "grant",
                        grantResults[index] == PackageManager.PERMISSION_GRANTED
                    )
                    jsonArray.put(jsonObject)
                }
            }
            result.success(jsonArray.toString())
//            activityPluginBinding?.removeRequestPermissionsResultListener(this)
            true
        } else false
    }
}